#coding: utf8
import os
import random
import string
import oss2
from settings import ENV

def upload(filename, file, file_path=''):
    # 首先初始化AccessKeyId、AccessKeySecret、Endpoint等信息。
    # 通过环境变量获取，或者把诸如“<你的AccessKeyId>”替换成真实的AccessKeyId等。
    #
    # 以杭州区域为例，Endpoint可以是：
    #   http://oss-cn-hangzhou.aliyuncs.com
    #   https://oss-cn-hangzhou.aliyuncs.com
    # 分别以HTTP、HTTPS协议访问。
    access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', 'LTAIjzYMUkyGRdpq')
    access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', 'sTbvM6C50e5Nk69Wn2T3QuPauACuGB')
    bucket_name = os.getenv('OSS_TEST_BUCKET', 'media-huanxi')
    endpoint = os.getenv('OSS_TEST_ENDPOINT', 'http://oss-cn-shanghai.aliyuncs.com')
    if ENV == 'aliyun':
        endpoint = os.getenv('OSS_TEST_ENDPOINT', 'http://oss-cn-shanghai-internal.aliyuncs.com')

    # 确认上面的参数都填写正确了
    for param in (access_key_id, access_key_secret, bucket_name, endpoint):
        assert '<' not in param, '请设置参数：' + param


    # 创建Bucket对象，所有Object相关的接口都可以通过Bucket对象来进行
    bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)

    bucket.put_object_from_file(filename, file_path) if file_path else bucket.put_object(filename, file)